<template>
  <view class="content" v-if="isShow" @click.stop="isShow=false">
    <canvas @click.stop :style="{ width: canvasW + 'px', height: canvasH + 'px' }" canvas-id="my-canvas"></canvas>
    <view class="save-btn" @click.stop="saveImage">保存相册，分享至朋友圈</view>
  </view>
</template>

<script>
export default {
  props: {
    headerImg: {
      type: String,
      default: 'https://oss.zhangyubk.com/%E8%8D%89%E8%8E%93%E5%8D%83%E5%B1%82.png'
    },
    title: {
      type: String,
      default: '草莓千层蛋糕'
    },
    time: {
      type: String,
      default: '草莓千层蛋糕'
    },
    week: {
      type: String,
      default: '草莓千层蛋糕'
    },
    biaoti: {
      type: String,
      default: '草莓千层蛋糕'
    },
    neirong: {
      type: String,
      default: '草莓千层蛋糕'
    },
    qrcode: {
      type: String,
      default: 'https://oss.zhangyubk.com/bottomab.png'
    },
    bgtu: {
      type: String,
      default: 'https://qiniuoss.yjqwl.cn/uploads/20220615/1a72dc6504e1d5fb0ddacc369d294519.png'
    },
    logoImg: {
      type: String,
      default: 'https://qiniuoss.yjqwl.cn/uploads/20220615/c80cea5ce12a8a4bcfcd38f3f7944fe2.png'
    },
    bgtu1: {
      type: String,
      default: 'https://qiniuoss.yjqwl.cn/uploads/20220616/1d0e786889df5fa32a181bada8a1f08d.png'
    },
    logoImg1: {
      type: String,
      default: 'https://qiniuoss.yjqwl.cn/uploads/20220616/08c673d7c2595c18fed71ab0190028a6.png'
    },
  },
  data() {
    return {
      canvasW: 0,
      canvasH: 0,
      ctx: null,
      isShow: false,
      // qrcode: 'https://gd.huijipin.cn/qrcode.jpg'
    }
  },
  methods: {

    //显示
    showCanvas() {
      let that = this


      // myFont.load().then(font => {
      //   document.fonts.add(font)
      // }).then(() => {
      //   const cvs = document.querySelector('canvas')
      //   const ctx = cvs.getContext('2d')

      //   ctx.font = '30px myFont'
      //   ctx.fillText('测试', 50, 50)
      // })
      this.isShow = true
      uni.getSystemInfo({
        success: function (res) {
          console.log(res.model);
          console.log(res.pixelRatio);
          console.log(res.windowWidth);
          console.log(res.windowHeight);
          console.log(res.language);
          console.log(res.version);
          console.log(res.platform);
          if (res.windowHeight > 672) {
            that.__init()
          } else {
            that.__init1()
          }
        }
      });
    },
    //初始化画布
    async __init() {
      uni.showLoading({
        title: '',
        mask: true
      })
      this.ctx = uni.createCanvasContext('my-canvas', this)
      // let myFont = new FontFace('myFont', 'url(../../font/HarmonyOS_Sans_SC_Medium.ttf)')
      // this.ctx.font = 'myFont'
      this.canvasW = uni.upx2px(700);
      this.canvasH = uni.upx2px(1300);


      //设置画布背景透明
      this.ctx.setFillStyle('rgba(255, 255, 255, 0)')
      //设置画布大小
      this.ctx.fillRect(0, 0, this.canvasW, this.canvasH)
      //绘制圆角背景
      this.drawRoundRect(this.ctx, 0, 0, this.canvasW, this.canvasH, uni.upx2px(30), '#FFFFFF')


      let bgtu = await this.getImageInfo(this.bgtu)
      let hW1 = uni.upx2px(700);
      let hH1 = uni.upx2px(1300);
      this.drawRoundImg(this.ctx, bgtu.path, 0, 0, hW1, hH1, 0)

      // 资讯属性
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#000'); //设置标题文本颜色
      let ti_hW = uni.upx2px(100);
      let ti_W = uni.upx2px(10);
      let ti_max = uni.upx2px(160);
      this.drawtext(this.ctx, this.title, (this.canvasW) / 9 - ti_W, (this.canvasH) / 7 + ti_hW, ti_max)
      // 时间
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#000'); //设置标题文本颜色
      let ti_hW1 = uni.upx2px(100);
      let ti_max1 = uni.upx2px(140);
      this.drawtext(this.ctx, this.time, (this.canvasW) / 9 + ti_max1, (this.canvasH) / 7 + ti_hW1, (this.canvasW) - ti_max1)

      // 星期
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#000'); //设置标题文本颜色
      let xing_hW = uni.upx2px(100);
      let xing_max = uni.upx2px(190);
      this.drawtext(this.ctx, this.week, this.canvasW - xing_max, (this.canvasH) / 7 + ti_hW1, (this.canvasW) / 7)

      // 内容
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#666'); //设置标题文本颜色
      let ti_hW3 = uni.upx2px(160);
      let ti_W3 = uni.upx2px(30);
      let ti_max3 = uni.upx2px(140);
      let max_neirong
      if (this.neirong.length > 316) {
        max_neirong = this.neirong.slice(0, 316) + '...'
      } else {
        max_neirong = this.neirong
      }
      this.drawtext(this.ctx, max_neirong, (this.canvasW) / 9 - ti_W, (this.canvasH) / 4 + ti_hW3, (this.canvasW) - ti_W3 * 4)


      // 标题
      let ti_hW2 = uni.upx2px(160);
      let ti_W2 = uni.upx2px(30);
      let ti_max2 = uni.upx2px(140);
      let max_biaoti
      if (this.biaoti.length > 34) {
        max_biaoti = this.biaoti.slice(0, 34) + '...'
      } else {
        max_biaoti = this.biaoti
      }
      this.wenzi_cu(max_biaoti, "normal bold 18px Arial", "#000000");
      this.drawtext1(this.ctx, max_biaoti, (this.canvasW) / 9 - ti_W, (this.canvasH) / 7 + ti_hW2, (this.canvasW) - ti_W2 * 4)





      // 冻品信息
      let qrcodeImg = await this.getImageInfo(this.logoImg)
      let erweima_h1 = uni.upx2px(420);
      let erweima_w1 = uni.upx2px(280);
      let hW_ewm1 = uni.upx2px(340);
      let hH_ewm1 = uni.upx2px(100);
      this.ctx.drawImage(qrcodeImg.path, (this.canvasW) / 2 - erweima_w1, (this.canvasH) / 2 + erweima_h1, hW_ewm1, hH_ewm1)


      //小程序码
      let qrcode = await this.getImageInfo(this.qrcode)
      let erweima_h = uni.upx2px(400);
      let erweima_w = uni.upx2px(120);
      let hW_ewm = uni.upx2px(140);
      let hH_ewm = uni.upx2px(140);
      this.ctx.drawImage(qrcode.path, (this.canvasW) / 2 + erweima_w, (this.canvasH) / 2 + erweima_h, hW_ewm, hH_ewm)


      // 扫码
      this.ctx.setFillStyle('#888888');
      this.ctx.setFontSize(10);
      let ti_ewm = uni.upx2px(110);
      let zi_ewm = uni.upx2px(110);
      this.drawtext(this.ctx, '扫码查看更多详情', (this.canvasW) / 2 + zi_ewm, this.canvasH - ti_ewm, (this.canvasW) / 2)



      //延迟渲染
      setTimeout(() => {
        this.ctx.draw(true, () => {
          uni.hideLoading()
        })
      }, 500)
    },

    // 小平
    async __init1() {
      uni.showLoading({
        title: '',
        mask: true
      })
      this.ctx = uni.createCanvasContext('my-canvas', this)
      this.canvasW = uni.upx2px(654);
      this.canvasH = uni.upx2px(1060);


      //设置画布背景透明
      this.ctx.setFillStyle('rgba(255, 255, 255, 0)')
      //设置画布大小
      this.ctx.fillRect(0, 0, this.canvasW, this.canvasH)
      //绘制圆角背景
      this.drawRoundRect(this.ctx, 0, 0, this.canvasW, this.canvasH, uni.upx2px(30), '#FFFFFF')


      let bgtu = await this.getImageInfo(this.bgtu1)
      let hW1 = uni.upx2px(654);
      let hH1 = uni.upx2px(1060);
      this.drawRoundImg(this.ctx, bgtu.path, 0, 0, hW1, hH1, 0)

      // 资讯属性
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#000'); //设置标题文本颜色
      let ti_hW = uni.upx2px(100);
      let ti_W = uni.upx2px(10);
      let ti_max = uni.upx2px(160);
      this.drawtext(this.ctx, this.title, (this.canvasW) / 9 - ti_W, (this.canvasH) / 7 + ti_hW, ti_max)
      // 时间
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#000'); //设置标题文本颜色
      let ti_hW1 = uni.upx2px(100);
      let ti_max1 = uni.upx2px(140);
      this.drawtext(this.ctx, this.time, (this.canvasW) / 9 + ti_max1, (this.canvasH) / 7 + ti_hW1, (this.canvasW) - ti_max1)

      // 星期
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#000'); //设置标题文本颜色
      let xing_hW = uni.upx2px(100);
      let xing_max = uni.upx2px(170);
      this.drawtext(this.ctx, this.week, this.canvasW - xing_max, (this.canvasH) / 7 + ti_hW1, (this.canvasW) / 7)




      // 内容
      this.ctx.setFontSize(13); //设置标题字体大小
      this.ctx.setFillStyle('#666'); //设置标题文本颜色
      let ti_hW3 = uni.upx2px(180);
      let ti_W3 = uni.upx2px(30);
      let ti_max3 = uni.upx2px(220);
      let max_neirong
      if (this.neirong.length > 176) {
        max_neirong = this.neirong.slice(0, 176) + '...'
      } else {
        max_neirong = this.neirong
      }
      this.drawtext(this.ctx, max_neirong, (this.canvasW) / 9 - ti_W, (this.canvasH) / 4 + ti_hW3, (this.canvasW) - ti_W3 * 4)

      // 标题
      let ti_hW2 = uni.upx2px(160);
      let ti_W2 = uni.upx2px(30);
      let ti_max2 = uni.upx2px(140);
      let max_biaoti
      if (this.biaoti.length > 32) {
        max_biaoti = this.biaoti.slice(0, 32) + '...'
      } else {
        max_biaoti = this.biaoti
      }
      this.wenzi_cu(max_biaoti, "normal bold 18px Arial", "#000000");
      this.drawtext1(this.ctx, max_biaoti, (this.canvasW) / 9 - ti_W, (this.canvasH) / 7 + ti_hW2, (this.canvasW) - ti_W2 * 4)


      // 冻品信息
      let qrcodeImg = await this.getImageInfo(this.logoImg1)
      let erweima_h1 = uni.upx2px(320);
      let erweima_w1 = uni.upx2px(256);
      let hW_ewm1 = uni.upx2px(310);
      let hH_ewm1 = uni.upx2px(90);
      this.ctx.drawImage(qrcodeImg.path, (this.canvasW) / 2 - erweima_w1, (this.canvasH) / 2 + erweima_h1, hW_ewm1, hH_ewm1)


      //小程序码
      let qrcode = await this.getImageInfo(this.qrcode)
      let erweima_h = uni.upx2px(300);
      let erweima_w = uni.upx2px(120);
      let hW_ewm = uni.upx2px(120);
      let hH_ewm = uni.upx2px(120);
      this.ctx.drawImage(qrcode.path, (this.canvasW) / 2 + erweima_w, (this.canvasH) / 2 + erweima_h, hW_ewm, hH_ewm)


      // 扫码
      this.ctx.setFillStyle('#888888');
      this.ctx.setFontSize(10);
      let ti_ewm = uni.upx2px(120);
      let zi_ewm = uni.upx2px(90);
      this.drawtext(this.ctx, '扫码查看更多详情', (this.canvasW) / 2 + zi_ewm, this.canvasH - ti_ewm, (this.canvasW) / 2)



      //延迟渲染
      setTimeout(() => {
        this.ctx.draw(true, () => {
          uni.hideLoading()
        })
      }, 500)
    },


    //绘制实心圆
    drawEmptyRound(ctx, x, y, radius) {
      ctx.save()
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
      ctx.setFillStyle('rgba(0, 0, 0, .4)')
      ctx.fill();
      ctx.restore()
      ctx.closePath()
    },
    //绘制虚线
    drawDashLine(ctx, x1, y1, x2, y2, dashLength) {
      ctx.setStrokeStyle("#cccccc")//设置线条的颜色
      ctx.setLineWidth(1)//设置线条宽度
      var dashLen = dashLength,
        xpos = x2 - x1, //得到横向的宽度;
        ypos = y2 - y1, //得到纵向的高度;
        numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen);
      //利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
      for (var i = 0; i < numDashes; i++) {
        if (i % 2 === 0) {
          ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
          //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
        } else {
          ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
        }
      }
      ctx.stroke();
    },
    //带圆角图片
    drawRoundImg(ctx, img, x, y, width, height, radius) {
      ctx.beginPath()
      ctx.save()
      // 左上角
      ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
      ctx.stroke()
      ctx.clip()
      ctx.drawImage(img, x, y, width, height);
      ctx.restore()
      ctx.closePath()
    },
    //圆角矩形
    drawRoundRect(ctx, x, y, width, height, radius, color) {
      ctx.save();
      ctx.beginPath();
      ctx.setFillStyle(color);
      ctx.setStrokeStyle(color)
      ctx.setLineJoin('round');  //交点设置成圆角
      ctx.setLineWidth(radius);
      ctx.strokeRect(x + radius / 2, y + radius / 2, width - radius, height - radius);
      ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
      ctx.stroke();
      ctx.closePath();
    },
    //获取图片
    getImageInfo(imgSrc) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: imgSrc,
          success: (image) => {
            resolve(image);
            console.log('获取图片成功', image)
          },
          fail: (err) => {
            reject(err);
            console.log('获取图片失败', err)
          }
        });
      });
    },
    //保存图片到相册
    saveImage() {
      //判断用户授权
      // uni.getSetting({
      //    success(res) {
      //       console.log('获取用户权限',res.authSetting)
      // 	  if(Object.keys(res.authSetting).length>0){
      // 		  //判断是否有相册权限
      // 		  if(res.authSetting['scope.writePhotosAlbum']==undefined){
      // 			  //打开设置权限
      // 			  uni.openSetting({
      // 			    success(res) {
      // 			      console.log('设置权限',res.authSetting)
      // 			    }
      // 			  })
      // 		  }else{
      // 			  if(!res.authSetting['scope.writePhotosAlbum']){
      // 				  //打开设置权限
      // 				  uni.openSetting({
      // 				    success(res) {
      // 				      console.log('设置权限',res.authSetting)
      // 				    }
      // 				  })
      // 			  }
      // 		  }
      // 	  }else{
      // 		  return
      // 	  }
      //    }
      // })
      var that = this
      uni.canvasToTempFilePath({
        canvasId: 'my-canvas',
        quality: 1,
        complete: (res) => {
          console.log('保存到相册', res);
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              uni.showToast({
                title: '已保存到相册',
                icon: 'success',
                duration: 2000
              })
              setTimeout(() => {
                that.isShow = false
              }, 2000)
            }
          })
        }
      }, this);
    },
    // 文字加粗
    wenzi_cu(text, font, fontColor) {
      this.ctx.font = font;
      this.ctx.fillStyle = fontColor;
    },
    // 文字换行
    drawtext(ctx, t, x, y, w) {
      //参数说明
      //ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，w：文字最大宽度
      let chr = t.split("")
      let temp = ""
      let row = []

      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < w && ctx.measureText(temp + (chr[a])).width <= w) {
          temp += chr[a];
        } else {
          row.push(temp);
          temp = chr[a];
        }
      }
      row.push(temp)
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b], x, y + (b + 1) * 20);//每行字体y坐标间隔20
      }

    },
    // 文字换行
    drawtext1(ctx, t, x, y, w) {
      //参数说明
      //ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，w：文字最大宽度
      let chr = t.split("")
      let temp = ""
      let row = []

      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < w && ctx.measureText(temp + (chr[a])).width <= w) {
          temp += chr[a];
        } else {
          row.push(temp);
          temp = chr[a];
        }
      }
      row.push(temp)
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b], x, y + (b + 1) * 26);//每行字体y坐标间隔20
      }

    },
  }
}
</script>

<style scoped lang="scss">
.content {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 5;
  .save-btn {
    // margin-top: 35rpx;
    color: #ffffff;
    background: #0078ff;
    line-height: 90rpx;
    width: 88%;
    margin: 20rpx auto 0;
    border-radius: 45rpx;
    text-align: center;
  }
}
</style>
